// 课程管理store
import { courseUpload, courseDownload, courseImport} from "../../api/course.js";

const state = {
    current: 0, // 存储批量导入的时候是第几步,
    courseRecord: [] // 存储导入文件中的课程数据
}

const mutations = { // mutations改变state中的数据
    SET_CURRENT_ONE: (state) => { // 将current修改为1
        state.current = 1
    },
    SET_CURRENT_ZERO: (state) => { // 将current修改为0
        state.current = 0
    },
    SET_COURSE_RECORD: (state, courseRecord) => { // 修改导入课程中的课程数据
        state.courseRecord = courseRecord
    },
    DELETE_COURSE: (state, courseId) => { // 删除courseId的课程元素
        for(var i = 0; i < state.courseRecord.length; i ++){
            if(state.courseRecord[i].courseId === courseId){
                state.courseRecord.splice(i, 1)
                break;
            }
        }
    },
    EDIT_COURSE: (state, courseRecord) => { // 修改课程信息
        for(var i = 0; i < state.courseRecord.length; i ++){
            if(state.courseRecord[i].courseId === courseRecord.courseId){
                state.courseRecord[i] = courseRecord
                break;
            }
        }
    }
}

const actions = { // 发送请求
    courseUpload({ commit }, data){ // 批量导入上传文件
        return new Promise((resolve, reject) => {
            courseUpload(data).then( data => {
                if(data.code === 1){ // 上传成功
                    commit('SET_CURRENT_ONE');
                    commit('SET_COURSE_RECORD', data.data.data);
                    resolve(data);
                }else{
                    reject(data)
                }
            })
        })
    },
    courseDownload(){ // 批量导入下载模板
        return new Promise((resolve, reject) => {
            courseDownload().then((data) => {
                if(data.code === 1){
                    resolve(data);
                }else{
                    reject(data);
                }
            })
        })
    },
    backPre({commit}){ // 回到上一步，改变current的值
        commit('SET_CURRENT_ZERO')
    },
    courseImport({commit, state}, token){ // 导入课程信息
        return new Promise((resolve, reject) => {
            courseImport({courses: state.courseRecord, token: token})
                .then((data) => {
                    if(data.code === 1){
                        commit('SET_CURRENT_ZERO')
                        resolve(data);
                    }else{
                        reject(data);
                    }
                })
        })
    },
    courseDelete({commit}, data){ // 删除课程
        const courseId = data.courseId
        commit('DELETE_COURSE', courseId);
    },
    courseModify({commit}, data){ // 修改课程信息
        const courseRecord = data.courseRecord
        commit('EDIT_COURSE', courseRecord);
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}
